package com.portal.framework.util;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.io.Resource;

public class SimplePropertiesSource implements PropertiesSource {
	private static final Log log = LogFactory
			.getLog(SimplePropertiesSource.class);
	private List<Resource> resources;
	private Properties p = null;

	public List<Resource> getResources() {
		return resources;
	}

	public void setResources(List<Resource> resources) {
		this.resources = resources;
	}

	public void addResources(Resource resource) {
		if (resources == null) {
			resources = new ArrayList<Resource>();
		}
		resources.add(resource);
	}

	public void setResources(Resource[] resources) {
		if (resources != null) {
			this.resources = Arrays.asList(resources);
		}
	}

	public Properties getProperties() {
		if (p != null) {
			return p;
		} else {
			p = new Properties();
		}

		if (resources == null) {
			return p;
		}

		if (log.isDebugEnabled()) {
			if (resources != null) {
				log.debug("resources 大小为 : " + resources.size());
				for (Resource r : resources) {
					try {
						log.debug("resources 路径 : ["
								+ r.getFile().getAbsolutePath() + "]");
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			} else {
				log.warn("resources 为空.");
			}
		}

		for (Resource res : resources) {
			try {
				p.load(res.getInputStream());
			} catch (IOException e) {
				if (log.isDebugEnabled()) {
					log.error(e.getMessage(), e);
				}
			}
		}
		return p;
	}

}
